package com.xa8bit.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.util.SaResult;
import com.xa8bit.enums.ResponseStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.naming.NoPermissionException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lingwh
 * @desc 全局异常处理类
 * @date 2025/11/22 17:35
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({
            NotLoginException.class,
            NoPermissionException.class,
            SaTokenException.class
    })
    public SaResult handleSaTokenException(Exception e) {
        // 日志记录异常信息
        log.error("Sa-Token 异常：{}", e.getMessage());

        ResponseStatus responseStatus = null;
        if (e instanceof NotLoginException) {
            NotLoginException nle = (NotLoginException) e;
            // 使用 switch 语句判断具体的未登录原因
            switch (nle.getType()) {
                case NotLoginException.NOT_TOKEN:
                    responseStatus = ResponseStatus.TOKEN_MISSING;
                    break;
                case NotLoginException.INVALID_TOKEN:
                    responseStatus = ResponseStatus.TOKEN_INVALID;
                    break;
                case NotLoginException.TOKEN_TIMEOUT:
                    responseStatus = ResponseStatus.TOKEN_EXPIRED;
                    break;
                case NotLoginException.BE_REPLACED:
                    responseStatus = ResponseStatus.TOKEN_REPLACED;
                    break;
                case NotLoginException.KICK_OUT:
                    responseStatus = ResponseStatus.TOKEN_KICK_OUT;
                    break;
                default:
                    // 涵盖其他可能的类型，如 NotLoginException.TOKEN_FREEZE
                    responseStatus = ResponseStatus.UNAUTHENTICATED;
                    break;
            }
        } else if (e instanceof NoPermissionException) {
            responseStatus = ResponseStatus.FORBIDDEN;
        } else {
            // 对于其他所有 Sa-Token 异常（如 NoRoleException），统一视为未授权
            responseStatus = ResponseStatus.UNAUTHENTICATED;
        }

        return SaResult.error(responseStatus.getMessage())
                .setCode(responseStatus.getCode());
    }

    /**
     * 全局异常处理，捕获所有未被其他异常处理程序捕获的异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public SaResult exceptionHandler(Exception e) {
        log.error("服务器内部错误!", e);
        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("e", e.toString());
        messageMap.put("desc", "服务器内部错误!");
        messageMap.put("msg", e.getMessage());
        return SaResult.error(messageMap.toString());
    }

}
